package org.xukai.common.util.guava;

import com.google.common.util.concurrent.*;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;

/**
 * @author xukai
 * @desc
 * @date 2016-11-15-下午 3:29
 */
public class Future {

    @Test
    public void test() throws ExecutionException, InterruptedException {
        ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
        ListenableFuture future = service.submit(new Callable() {
            public String call() {
                return "test1111";
            }
        });
        ListenableFuture future2 = service.submit(new Callable() {
            public String call() {
                return "test2222";
            }
        });
        ListenableFuture future3 = service.submit(new Callable() {
            public String call() {
                return "test3333";
            }
        });
        List<ListenableFuture> list = Arrays.asList(future, future2,future3);
        ListenableFuture successfulAsList = Futures.successfulAsList((Iterable) list);
        List<String> futures = (List<String>) successfulAsList.get();
        for (String result : futures){
            System.out.println(result);
        }
        Futures.addCallback(future, new FutureCallback() {
            // we want this handler to run immediately after we push the big red button!
            @Override
            public void onSuccess(Object explosion) {
                System.out.println(explosion);
            }
            public void onFailure(Throwable thrown) {
                thrown.getMessage(); // escaped the explosion!
            }
        });
    }



}
